import { Request, Response, NextFunction } from "express";
import mongoose from "mongoose";
import { MongoServerError, MongoError } from "mongodb";

interface ErrorResponse {
  statusCode: number;
  error: string;
  message: string;
  details?: Record<string, any>;
}

export function mongoErrorHandler(
  err: any,
  req: Request,
  res: Response<ErrorResponse>,
  next: NextFunction
) {
  if (err instanceof MongoError) {
    let statusCode = 400;
    let message = err.message;
    let error = err.name;
    let details: Record<string, any> | undefined;
    if (err instanceof MongoServerError) {
      if (err.code === 11000) {
        error = "Conflict";
        message = `字段 ${Object.keys(err.keyPattern)[0]} 重复`;
        details = {
          duplicateKey: err.keyValue,
          code: err.code,
          index: err.index,
        };
      }
    }

    return res.status(statusCode).json({
      statusCode,
      error,
      message,
      ...(details && { details }),
    });
  }

  // 不是 mongo 错误，继续往后传
  next(err);
}
